package com.duowan.cms.domain.article;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.duowan.cms.common.domain.DomainObject;
import com.duowan.cms.common.util.IdManager;
import com.duowan.cms.common.util.PathUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.domain.channel.Channel;
import com.duowan.cms.dto.article.ArticleInfo;
import com.duowan.cms.dto.article.ArticleStatus;

/**
 * 文章
 *
 * <br>==========================
 * <br> 公司：欢聚时代
 * <br> 开发：qiusidi@yy.com
 * <br> 版本：1.0
 * <br> 创建时间：2012-09-04
 * <br>==========================
 * alter 2013-03-07: 多问(Y世界),有爱项目关闭 
 */
public class Article implements DomainObject {

    private static final long serialVersionUID = -5944227675675991871L;

    public static Logger logger = Logger.getLogger(Article.class);

    /**
     * 唯一标识符
     */
    private Long id;

    /**
     * 频道id
     */
    private Channel channel;

    /**
     * 标题
     */
    private String title;
    /**
     * 标题颜色
     */
    private String titleColor;
    /**
     * 子标题
     */
    private String subtitle;
    /**
     * 摘要
     */
    private String digest;
    /**
     * 头图图片地址
     */
    private String pictureUrl;
    // /**
    // * 标签图图片地址
    // */
    // private String tagPictureUrl;
    /**
     * 来源
     */
    private String source;
    /**
     * 作者
     */
    private String author;
    /**
     * 发布时间（精确到秒）
     */
    private Date publishTime;
    /**
     * 预定发布时间（精确到秒）
     */
    private Date prePublishTime;
    /**
     * 最后修改时间
     */
    private Date lastUpdateTime;
    /**
     * 标签列表（多个标签使用“，”分割）所有标签
     */
    private String tags;
    /**
     * 发布者ID
     */
    private String userId;
    /**
     * 最后修改者ID
     */
    private String lastUpdateUserId;
    /**
     * 用户IP地址
     */
    private String userIp;
    /**
     * 用户使用的代理IP地址
     */
    private String proxyIp;
    /**
     * 文章的状态(0普通，1预定，2未加tag，3抓取，4用户投稿，99删除)
     */
    private ArticleStatus status;
    /**
     * 文章的操作记录
     */
    private String logs;
    /**
     * 详细内容
     */
    private String content;
    /**
     * 天数
     */
    private Integer dayNum;
    /**
     * 文章权重，一般用于排序
     */
    private Integer power = 1;
    /**
     * 对应的评论帖子ID
     */
    private Long threadId;
    /**
     * 模板ID
     */
    private Long templateId;
    /**
     * 相关联的标签，所有标签中去除了特殊标签
     */
    private String realtags;
    /**
     * 是否有头图
     */
    private String isHeadPic;
    /**
     * 自定义内容1
     */
    private String diy1;
    /**
     * 自定义内容2
     */
    private String diy2;
    /**
     * 自定义内容3
     */
    private String diy3;
    /**
     * 自定义内容4
     */
    private String diy4;
    /**
     * 自定义内容5
     */
    private String diy5;
    /**
     * 文章抓取的URL
     */
    private String catchUrl;
    // /**
    // * 空链接URL
    // */
    // private String emptyLink;
    /**
     * 是否单页显示全部(生成模板使用)
     */
    private boolean showAllPage;
    /**
     * 是否同步到Y世界（即多问）
     */
    // private boolean syncQa;
    /**
     * 是否同步WAP系统
     */
    private boolean syncWap;

    /**
     * 是否同步到有爱
     */
    // private boolean syncZone;

    /**
     * // 创建文章实体，检验值是否正确，并且赋值
     * 
     * @param articleInfo
     */
    public Article(ArticleInfo articleInfo) {
        this.id = articleInfo.getId();
        // 初始化文章的状态
        this.status = ArticleStatus.NORMAL;
        this.dayNum = IdManager.id2DayNum(this.id);
        this.userId = articleInfo.getUserId();// 编辑显示发表人,修改文章时不更新编辑
        this.publishTime = new Date();
        this.update(articleInfo);
    }

    public Article update(ArticleInfo articleInfo) {
        // 发布时间
        if (articleInfo.getPublishTime() != null)
            this.publishTime = articleInfo.getPublishTime();
        // 修改化文章的状态
        ArticleStatus articleStatus = null;
        if (articleInfo.getPrePublishTime() != null && new Date().before(articleInfo.getPrePublishTime())) {// 如果当前时间在预定发布时间之前，则状态设为预定发布
            articleStatus = ArticleStatus.PER_PUBLISH; // 预发布
            //将daynum改为预发布时间的dayNum
            this.dayNum = IdManager.id2DayNum(IdManager.generateIdByDate(articleInfo.getPrePublishTime()));
        } else if (StringUtil.isEmpty(articleInfo.getTags())) {
            articleStatus = ArticleStatus.NO_TAG; // 无tag
        } else {
            articleStatus = ArticleStatus.NORMAL;// 正常
        }
        // 判断是否有头图
        String isPic = null;
        String randomPicUrl = null;
        if (StringUtil.isEmpty(articleInfo.getPictureUrl())) {
            isPic = "no";
        } else {
            randomPicUrl = this.randomPicUrl(articleInfo.getPictureUrl()); // 多玩图片URL的域名做随机处理，替换为
            isPic = "yes";
        }
        this.channel = new Channel(articleInfo.getChannelInfo());// this.getChannelRepository().getById(articleInfo.getChannelInfo().getId());
                                                                 // // 取得频道
        this.isHeadPic = isPic;
        this.status = articleStatus;
        this.tags = articleInfo.getTags();
        this.realtags = articleInfo.getRealtags();
        this.threadId = articleInfo.getThreadId();
        this.title = articleInfo.getTitle();
        this.titleColor = articleInfo.getTitleColor();
        if (articleInfo.getLastUpdateTime() != null) {
            this.lastUpdateTime = articleInfo.getLastUpdateTime();
        } else {
            this.lastUpdateTime = new Date();
        }
        this.author = articleInfo.getAuthor();
        this.content = articleInfo.getContent();
        this.subtitle = articleInfo.getSubtitle();
        this.templateId = articleInfo.getTemplateId();
        this.userIp = articleInfo.getUserIp();
        this.lastUpdateUserId = articleInfo.getLastUpdateUserId();
        this.logs = articleInfo.getLogs();
        this.pictureUrl = randomPicUrl;
        this.power = articleInfo.getPower();
        this.prePublishTime = articleInfo.getPrePublishTime();
        this.proxyIp = articleInfo.getProxyIp();
        this.source = articleInfo.getSource();
        this.catchUrl = articleInfo.getCatchUrl();
        this.digest = articleInfo.getDigest();
        this.diy1 = articleInfo.getDiy1();
        this.diy2 = articleInfo.getDiy2();
        this.diy3 = articleInfo.getDiy3();
        this.diy4 = articleInfo.getDiy4();
        this.diy5 = articleInfo.getDiy5();
        // this.emptyLink = articleInfo.getEmptyLink();
        this.showAllPage = articleInfo.isShowAllPage();
        // this.syncQa = articleInfo.isSyncQa();
        this.syncWap = articleInfo.isSyncWap();
        // this.syncZone = articleInfo.isSyncZone();
        // this.tagPictureUrl = articleInfo.getTagPictureUrl();
        return this;
    }

    /**
     * 不对外提供
     */
    public Article() {
    }

    public List<Article4TagList> toArticle4TagList() {
        List<Article4TagList> list = new ArrayList<Article4TagList>();
        // 预发布的文章不予转化
        if (null == this.status || ArticleStatus.PER_PUBLISH == this.status)
            return list;
        String tags = this.tags;
        for (String tag : tags.split(",")) {
            if (StringUtil.isEmpty(tag)) {
                continue;
            }
            Article4TagList a = new Article4TagList();
            a.setChannel(this.channel);
            a.setTag(tag);
            a.setId(this.id);
            a.setTitle(this.title);
            a.setTitleColor(this.titleColor);
            a.setSubtitle(this.subtitle);
            a.setDigest(this.digest);
            // a.setEmptyLink(this.emptyLink);
            a.setPictureUrl(this.pictureUrl);
            a.setSource(this.source);
            a.setAuthor(this.author);
            a.setUserId(this.userId);
            a.setDayNum(this.dayNum);
            a.setPower(this.power);
            a.setPublishTime(this.publishTime);
            a.setUpdateTime(this.lastUpdateTime);
            a.setIsHeadPic(this.isHeadPic);
            a.setDiy1(this.diy1);
            a.setDiy2(this.diy2);
            a.setDiy3(this.diy3);
            a.setDiy4(this.diy4);
            a.setDiy5(this.diy5);
            a.setDelete(false);

            list.add(a);
        }
        return list;
    }

    public void resetDayNum() {
        // 该方法只是改变文章实例的状态，外部调用之后需要调用仓库层将之持久化
        this.dayNum = IdManager.id2DayNum(this.id);
    }

    /**
     * 发布文章
     */
    public void publish() {

    }

    /**
     * 正式环境的url:外网访问的url.
     * 使用到的地方:点击滚动文章列表，具体文章的标题旁的"实心五角星"访问的url
     * 举例:urlOnLine的格式类似http://wow.duowan.com/1209/211821276072.html这样的链接
     */
    public String getUrlOnLine() {
        // if(!StringUtil.isEmpty(emptyLink))
        // return emptyLink;
        // else
        return PathUtil.getArticleOnlineUrl(this.getChannel().getDomain(), id);
    }

    /**
     * 发布器服务器上的url.
     * 使用到的地方:点击滚动文章列表，具体文章的标题旁的"空心五角星"访问的url
     * 举例:urlOnCms的格式类似http://cms.duowan.com/wow/1209/211821276072.html这样的链接
     */
    public String getUrlOnCms() {
        return PathUtil.getArticleOnCmsUrl(this.getChannel().getId(), id);
    }

    /**
     * pic.duowan.com域名做随机处理
     * @param url
     * @return
     */
    // TODO pic.duowan.com --> img.duowan.com
    private String randomPicUrl(String url) {
        if (StringUtil.isEmpty(url))
            return "";
        String pic = "pic";
        int x = 0;
        while ((x = (int) (Math.random() * 6)) == 0) {
        }
        pic += x;
        return url.replaceFirst("pic.duowan.com", pic + ".duowan.com");
    }

    public String getTitleColor() {
        return titleColor;
    }

    public void setTitleColor(String titleColor) {
        this.titleColor = titleColor;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDiy4() {
        return diy4;
    }

    public void setDiy4(String diy4) {
        this.diy4 = diy4;
    }

    public String getDiy5() {
        return diy5;
    }

    public void setDiy5(String diy5) {
        this.diy5 = diy5;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public String getDigest() {
        return digest;
    }

    public void setDigest(String digest) {
        this.digest = digest;
    }

    public String getPictureUrl() {
        return pictureUrl;
    }

    public void setPictureUrl(String pictureUrl) {
        this.pictureUrl = pictureUrl;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getPublishTime() {
        return publishTime;
    }

    public void setPublishTime(Date publishTime) {
        this.publishTime = publishTime;
    }

    public Date getPrePublishTime() {
        return prePublishTime;
    }

    public void setPrePublishTime(Date prePublishTime) {
        this.prePublishTime = prePublishTime;
    }

    public Date getLastUpdateTime() {
        return lastUpdateTime;
    }

    public void setLastUpdateTime(Date lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
    }

    public String getTags() {
        return tags;
    }

    public void setTags(String tags) {
        this.tags = tags;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getLastUpdateUserId() {
        return lastUpdateUserId;
    }

    public void setLastUpdateUserId(String lastUpdateUserId) {
        this.lastUpdateUserId = lastUpdateUserId;
    }

    public String getUserIp() {
        return userIp;
    }

    public void setUserIp(String userIp) {
        this.userIp = userIp;
    }

    public String getProxyIp() {
        return proxyIp;
    }

    public void setProxyIp(String proxyIp) {
        this.proxyIp = proxyIp;
    }

    public ArticleStatus getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = ArticleStatus.getInstance(status);
    }

    public String getLogs() {
        return logs;
    }

    public void setLogs(String logs) {
        this.logs = logs;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Integer getDayNum() {
        return dayNum;
    }

    public void setDayNum(Integer dayNum) {
        this.dayNum = dayNum;
    }

    public Integer getPower() {
        return power;
    }

    public void setPower(Integer power) {
        this.power = power;
    }

    public Long getThreadId() {
        return threadId;
    }

    public void setThreadId(Long threadId) {
        this.threadId = threadId;
    }

    public Long getTemplateId() {
        return templateId;
    }

    public void setTemplateId(Long templateId) {
        this.templateId = templateId;
    }

    public String getRealtags() {
        return realtags;
    }

    public void setRealtags(String realtags) {
        this.realtags = realtags;
    }

    public String getIsHeadPic() {
        return isHeadPic;
    }

    public void setIsHeadPic(String isHeadPic) {
        this.isHeadPic = isHeadPic;
    }

    public String getDiy1() {
        return diy1;
    }

    public void setDiy1(String diy1) {
        this.diy1 = diy1;
    }

    public String getDiy2() {
        return diy2;
    }

    public void setDiy2(String diy2) {
        this.diy2 = diy2;
    }

    public String getDiy3() {
        return diy3;
    }

    public void setDiy3(String diy3) {
        this.diy3 = diy3;
    }

    public String getCatchUrl() {
        return catchUrl;
    }

    public void setCatchUrl(String catchUrl) {
        this.catchUrl = catchUrl;
    }

    // public String getTagPictureUrl() {
    // return tagPictureUrl;
    // }
    //
    // public void setTagPictureUrl(String tagPictureUrl) {
    // this.tagPictureUrl = tagPictureUrl;
    // }

    // private ChannelRepository getChannelRepository(){
    // return SpringApplicationContextHolder.getBean("channelRepository",
    // ChannelRepository.class);
    // }

    // public String getEmptyLink() {
    // return emptyLink;
    // }
    //
    // public void setEmptyLink(String emptyLink) {
    // this.emptyLink = emptyLink;
    // }

    public boolean isShowAllPage() {
        return showAllPage;
    }

    public void setShowAllPage(boolean showAllPage) {
        this.showAllPage = showAllPage;
    }

    public boolean isSyncWap() {
        return syncWap;
    }

    public void setSyncWap(boolean syncWap) {
        this.syncWap = syncWap;
    }

}